$( document ).ready( function(){
	$("#addUserStory").click(function(){
		$("#userStoryDetail").load('/user_stories/new');
	});
	
	var markedStories = new Array();
	var deleteModus = false;
	
	$( document ).on("click", ".userStory", function(){
		var parts = this.id.split("_");
		var id = parts[1];
		if(deleteModus){
			
			if($.inArray(id, markedStories) >= 0){
				markedStories.splice($.inArray(id, markedStories), 1);
				$("#"+this.id).removeClass("marked");
			}else{
				markedStories.push(id);
				$("#"+this.id).addClass("marked");
			}
		}else{
			//Edit Mode
			$("#userStoryDetail").load('/user_stories/edit?id='+id);
		}
	});
	
    $("#deleteUserStory").click(function(){
    	if(deleteModus){
	    	if(markedStories.length > 0){
	    		var items = "";
	        	
	        	markedStories.forEach(function logArrayElements(element, index, array) {
	        		items += element+",";
	        	});
	        	
	        	items = items.substring(0, items.length-1);
	        	
	        	if(confirm("Die User Stories:\n\n"+items+"\n\nwerden unwiederruflich gelöscht.")){
	        		$.getJSON( "../user_stories/delete?items="+items).done(function( data ) {
	        			if(data != "0"){
	        				var itemsNotDeleted = "";
	
	        				if(data.length > 0){
		        				$.each( data.items, function( i, item ) {
		        					markedStories.splice($.inArray(item, markedStories), 1);
		        					itemsNotDeleted += item+",";
		        			    });	
	        				}else{
	        					markedStories.splice($.inArray(data, markedStories), 1);
	        					itemsNotDeleted += data+",";
	        				}
	
	        				$.each( data, function( i, item ) {
	        					markedStories.splice($.inArray(item, markedStories), 1);
	        					itemsNotDeleted += item+",";
	        			    });
			
	        				if(itemsNotDeleted != ""){
	        					itemsNotDeleted = itemsNotDeleted.substring(0, itemsNotDeleted.length-1);
	        					alert("Items: \n\n" + itemsNotDeleted + "\n\n konnten nicht gelöscht werden!");
	        				}
	        			}
	        			
	                	markedStories.forEach(function logArrayElements(element, index, array) {
	                		$("#userStory_"+element).fadeOut(200);
	                	});
	                	
	                	markedStories = new Array();
	        		});
	        	}
	        	
	        	deleteModus = false;
	    	}else{
	    		alert("Bitte wählen sie User Stories aus der Liste!");
	    	}
    	}else{
    		deleteModus=true;
    	}
    });
});